import { Button, Cascader, DatePicker, Input, InputNumber, Select } from "antd";
import { useTranslation } from "react-i18next";
const { RangePicker } = DatePicker;
import classNames from "classnames";
import {
  formatDate,
  filterWarehouseData,
  returnOrderOptions,
  IPageConfig,
} from "@/utils";
import { useSelector } from "react-redux";
import { IStore } from "@/store";
import dayjs from "dayjs";
import { VerticalAlignTopOutlined } from "@ant-design/icons";
import { useEffect, useImperativeHandle, useState } from "react";
import { DefaultOptionType } from "antd/es/cascader";
interface ICustomerProps {
  search: any;
  setSearch: any;
  initData: any;
  handlerSearchClick: () => void;
  pageConfig: IPageConfig[];
  handlerAddClick: any;
  title: string;
  children?: React.ReactNode;
}
const CustomForm = ({
  pageConfig,
  search,
  setSearch,
  initData,
  handlerSearchClick,
  handlerAddClick,
  title,
  children,
}: ICustomerProps) => {
  const { t } = useTranslation();
  const store = useSelector((state: IStore) => state.user);
  function exportConfig() {
    const str = pageConfig.map((item) => {
      if (typeof search[item.key] != "object") {
        return search[item.key]
          ? item.key + "=" + search[item.key]
          : item.key + "=";
      } else {
        return search[item.key].join(",")
          ? item.key + "=" + search[item.key].join(",")
          : item.key + "=";
      }
    });
    return `http://localhost:12345/export?title=${title}&` + str.join("&");
  }
  const [hidden, SetHidden] = useState(true);
  function handleResetClick() {
    setSearch({});
    initData();
  }
  useEffect(() => {
    function HandleKeyUp(evt: KeyboardEvent) {
      if (evt.ctrlKey && evt.code === "Enter") {
        handlerSearchClick();
      }
      if (evt.ctrlKey && evt.code === "KeyR") {
        evt.preventDefault();
        handleResetClick();
      }
      if (evt.ctrlKey && evt.altKey && evt.code === "KeyD") {
        window.open(exportConfig(), "_blank");
      }
      if (evt.ctrlKey && evt.altKey && evt.code === "KeyA") {
        evt.preventDefault();
        handlerAddClick();
      }
    }
    window.addEventListener("keydown", HandleKeyUp);
    return () => {
      window.removeEventListener("keydown", HandleKeyUp);
    };
  }, [search]);
  useEffect(() => {
    if (store.innerWidth < 1024) {
      SetHidden(true);
    } else {
      SetHidden(false);
    }
  }, [store.innerWidth]);
  useImperativeHandle(null, () => {
    return {
      hidden,
    };
  });
  return (
    <div className="custom-form">
      <div
        className={classNames([
          hidden ? "h-0" : "sm:h-72 md:h-32 lg:h-20",
          "transition-all mb-1 flex flex-wrap overflow-auto",
        ])}
      >
        {pageConfig.map((item: IPageConfig) => {
          return (
            <div
              key={item.key}
              className="sm:w-full md:w-1/3 lg:w-1/4 mb-1 px-1"
            >
              {item.type == "string" && (
                <Input
                  value={search[item.key]}
                  onChange={(val) =>
                    setSearch({
                      ...search,
                      [item.key]: val.target.value,
                    })
                  }
                  onKeyDown={(evt) => {
                    if (evt.code == "Enter") handlerSearchClick();
                  }}
                  allowClear
                  placeholder={t(item.placeholder)}
                ></Input>
              )}

              {item.type == "number" && (
                <InputNumber
                  type="number"
                  className="w-full"
                  value={search[item.key]}
                  onChange={(val) =>
                    setSearch({
                      ...search,
                      [item.key]: val,
                    })
                  }
                  onKeyDown={(evt) => {
                    if (evt.code == "Enter") handlerSearchClick();
                  }}
                  placeholder={t(item.placeholder) + "   Ctrl + Enter 搜索"}
                ></InputNumber>
              )}

              {item.type == "custom" && (
                <Select
                  className="w-full"
                  listHeight={store.innerWidth > 1024 ? 300 : 150}
                  onChange={(val) =>
                    setSearch({
                      ...search,
                      [item.key]: val,
                    })
                  }
                  onInputKeyDown={(event) => {
                    if (event.ctrlKey && search[item.key] != undefined)
                      handlerSearchClick();
                  }}
                  allowClear
                  value={search[item.key]}
                  options={returnOrderOptions(item.key, store.users)}
                  placeholder={t(item.placeholder)}
                ></Select>
              )}
              {item.type == "date" && (
                <input
                  id="input_date"
                  onKeyDown={(event) => {
                    if (
                      event.ctrlKey &&
                      event.code === "Enter" &&
                      search[item.key] != undefined
                    )
                      handlerSearchClick();
                  }}
                  value={dayjs(search.outbound_date).format("YYYY-MM-DD")}
                  type="date"
                  onChange={(val) =>
                    setSearch({
                      ...search,
                      [item.key]: val,
                    })
                  }
                  className="w-full px-2 py-1 border bg-white"
                />
              )}
              {item.type == "datePick" && (
                <RangePicker
                  onKeyDown={(event) => {
                    if (event.ctrlKey) handlerSearchClick();
                  }}
                  className="w-full px-2 py-1 border bg-white"
                  placeholder={[
                    t("formTimeSelectStart"),
                    t("formTimeSelectEnd"),
                  ]}
                  onChange={(_, date) => {
                    setSearch({
                      ...search,
                      time: date.join(","),
                    });
                  }}
                />
              )}
            </div>
          );
        })}
      </div>
      <div className="mb-1 sm:justify-start lg:justify-end items-center flex gap-1 overflow-auto ">
        <div>
          <VerticalAlignTopOutlined
            onClick={() => SetHidden(!hidden)}
            className={`${store.innerWidth > 1024 ? "text-2xl" : "text-xl"} ${
              hidden && "rotate-180"
            } w-6 duration-500 transition-all`}
          />
        </div>
        {children}
        <Button
          size={store.innerWidth > 1024 ? "middle" : "small"}
          onClick={() => handlerSearchClick()}
          type="primary"
        >
          {t("search")}
        </Button>
        <Button
          size={store.innerWidth > 1024 ? "middle" : "small"}
          onClick={() => handleResetClick()}
          type="primary"
        >
          {t("reset")}
        </Button>
        <Button
          size={store.innerWidth > 1024 ? "middle" : "small"}
          onClick={() => handlerAddClick()}
          type="primary"
        >
          {t("add")}
        </Button>
        <Button
          size={store.innerWidth > 1024 ? "middle" : "small"}
          type="primary"
        >
          <a target="_blank" href={exportConfig()}>
            {t("export")}
          </a>
        </Button>
      </div>
    </div>
  );
};
export default CustomForm;
